#include "csb.h"
//************超声波测距*************
#include <intrins.h>
sbit TX=P1^0;
sbit RX=P1^1;

void Delay12us()		//@12.000MHz   12us
{
	unsigned char i;

	_nop_();
	_nop_();
	i = 33;
	while (--i);
}

void Send_wave()	//产生8个40KHx超声波信号
{
	unsigned char i;
	for(i=0;i<8;i++)
	{
		TX = 1;
		Delay12us();
		TX = 0;
		Delay12us();
	}
}

unsigned int mea_csb()				//超声波测距
{
	unsigned int time=0;
	static unsigned int distance = 0;

	TMOD &= 0X0F;			//定时器1模式0,13位，最大8192个计数脉冲
	TL1 = 0X00;
	TH1 = 0X00;
	
	Send_wave();			//发送超声波信号
	TR1 = 1;				//启动定时器
	while((RX==1)&&(TF1==0));	//等待超声波信号返回或者等到测量超出范围
	TR1 = 0;					//关闭定时器					
			
	if(TF1)						//正常测量范围
	{
		TF1=0;
		distance = 999;
	}
	else						//超出测量范围
	{
		time = (TH1<<8)|TL1;
		distance = (time/10*17)/100+3;
	}

    return distance;
}
